package com.yzy.util.oss;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import com.yzy.properties.GlobalProperties;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 腾讯云
 */
@Component
public class TencentCloudUtil {

    @Resource
    private GlobalProperties globalProperties;

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    /**
     * 上传文件重命名UUID
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws IOException {
        Date date = new Date();
        String fileName = formatter.format(date);
        // 创建coSClient实例。

        COSCredentials cred = new BasicCOSCredentials(globalProperties.getCosSecretId(), globalProperties.getCosSecretkey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(globalProperties.getCosRegin()));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));

        fileName = fileName + "/" + UUID.randomUUID() + suffixName;

        // 上传文件流。
        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度
        objectMetadata.setContentLength(inputStream.available());
        // 设置 Content type, 默认是 application/octet-stream
        //objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(globalProperties.getCosBucketName(), fileName, inputStream, objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);

        PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        String eString = putObjectResult.getETag();

        //System.out.println("estring====="+eString);
        // 关闭OSSClient。
        cosclient.shutdown();
        return globalProperties.getCosFilePath() + fileName;
    }

    /**
     * 上传文件保留原名字
     * @param file
     * @return dir 自定义文件夹名字
     * @throws Exception
     */
    public String uploadFileKeepName(MultipartFile file, String dir) throws Exception {
        Date date = new Date();
        String filename = formatter.format(date);
        // 创建coSClient实例。
        COSCredentials cred = new BasicCOSCredentials(globalProperties.getCosSecretId(), globalProperties.getCosSecretkey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(globalProperties.getCosRegin()));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        //String dateStr = formatter.format(date);
        // 上传文件流。

        if (StringUtils.isNotBlank(dir)) {
            filename = dir + "/" + originalFilename;
        } else {
            filename = filename + "/" + originalFilename;
        }
        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度
        objectMetadata.setContentLength(inputStream.available());
        // 设置 Content type, 默认是 application/octet-stream
        //objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(globalProperties.getCosBucketName(), filename, inputStream, objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);

        PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        String eString = putObjectResult.getETag();

        //System.out.println("estring====="+eString);
        // 关闭OSSClient。
        cosclient.shutdown();
        return globalProperties.getCosFilePath() + filename;
    }


    /**
     * 上传apk
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadFileApk(MultipartFile file, String dir) throws Exception {
        Date date = new Date();
        // 创建coSClient实例。
        COSCredentials cred = new BasicCOSCredentials(globalProperties.getCosSecretId(), globalProperties.getCosSecretkey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(globalProperties.getCosRegin()));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        // 上传文件流。
        String filename = dir + "/" + "gdb.apk";
        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度
        objectMetadata.setContentLength(inputStream.available());
        // 设置 Content type, 默认是 application/octet-stream
        //objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(globalProperties.getCosBucketName(), filename, inputStream, objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);

        PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        String eString = putObjectResult.getETag();

        //System.out.println("estring====="+eString);
        // 关闭OSSClient。
        cosclient.shutdown();
        return globalProperties.getCosFilePath() + filename;
    }

    private static FileItem createFileItem(String filePath) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "textField";
        int num = filePath.lastIndexOf(".");
        String extFile = filePath.substring(num);
        FileItem item = factory.createItem(textFieldName, "text/plain", true,
                "MyFileName" + extFile);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192))
                    != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    /*public static void main(String[] args) {
        toMultipartFile("D:\\zhuapai.jpg");
    }*/
    public String csUploadFile(MultipartFile file) throws Exception {
        Date date = new Date();
        String fileName = formatter.format(date);
        // 创建coSClient实例。
        COSCredentials cred = new BasicCOSCredentials(globalProperties.getCosSecretId(), globalProperties.getCosSecretkey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(globalProperties.getCosRegin()));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        //获取文件名
        //String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffixName = ".jpeg";

        fileName = fileName + "/" + UUID.randomUUID() + suffixName;

        // 上传文件流。
        InputStream inputStream = file.getInputStream();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度
        objectMetadata.setContentLength(inputStream.available());
        // 设置 Content type, 默认是 application/octet-stream
        //objectMetadata.setContentType("image/jpeg");

        PutObjectRequest putObjectRequest = new PutObjectRequest(globalProperties.getCosBucketName(), fileName, inputStream, objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);

        PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
        String eString = putObjectResult.getETag();

        //System.out.println("estring====="+eString);
        // 关闭OSSClient。
        cosclient.shutdown();
        return globalProperties.getCosFilePath() + fileName;
    }
}
